{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model Selection - Cross Validation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# import the packages\n",
    "from pyspark.ml import Pipeline\n",
    "from pyspark.ml.classification import LogisticRegression\n",
    "from pyspark.ml.evaluation import BinaryClassificationEvaluator\n",
    "from pyspark.ml.feature import HashingTF, Tokenizer\n",
    "from pyspark.ml.tuning import CrossValidator, ParamGridBuilder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prepare training documents, which are labeled.\n",
    "training = spark.createDataFrame([\n",
    "    (0, \"a b c d e spark\", 1.0),\n",
    "    (1, \"b d\", 0.0),\n",
    "    (2, \"spark f g h\", 1.0),\n",
    "    (3, \"hadoop mapreduce\", 0.0),\n",
    "    (4, \"b spark who\", 1.0),\n",
    "    (5, \"g d a y\", 0.0),\n",
    "    (6, \"spark fly\", 1.0),\n",
    "    (7, \"was mapreduce\", 0.0),\n",
    "    (8, \"e spark program\", 1.0),\n",
    "    (9, \"a e c l\", 0.0),\n",
    "    (10, \"spark compile\", 1.0),\n",
    "    (11, \"hadoop software\", 0.0)\n",
    "], [\"id\", \"text\", \"label\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Configure an ML pipeline, which consists of tree stages: tokenizer, hashingTF, and lr.\n",
    "tokenizer = Tokenizer(inputCol=\"text\", outputCol=\"words\")\n",
    "hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol=\"features\")\n",
    "lr = LogisticRegression(maxIter=10)\n",
    "pipeline = Pipeline(stages=[tokenizer, hashingTF, lr])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# We now treat the Pipeline as an Estimator, wrapping it in a CrossValidator instance.\n",
    "# This will allow us to jointly choose parameters for all Pipeline stages.\n",
    "# A CrossValidator requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.\n",
    "# We use a ParamGridBuilder to construct a grid of parameters to search over.\n",
    "# With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,\n",
    "# this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.\n",
    "paramGrid = ParamGridBuilder() \\\n",
    "    .addGrid(hashingTF.numFeatures, [10, 100, 1000]) \\\n",
    "    .addGrid(lr.regParam, [0.1, 0.01]) \\\n",
    "    .build()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "crossval = CrossValidator(estimator=pipeline,\n",
    "                          estimatorParamMaps=paramGrid,\n",
    "                          evaluator=BinaryClassificationEvaluator(),\n",
    "                          numFolds=2)  # use 3+ folds in practice"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run cross-validation, and choose the best set of parameters.\n",
    "cvModel = crossval.fit(training)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prepare test documents, which are unlabeled.\n",
    "test = spark.createDataFrame([\n",
    "    (4, \"spark i j k\"),\n",
    "    (5, \"l m n\"),\n",
    "    (6, \"mapreduce spark\"),\n",
    "    (7, \"apache hadoop\")\n",
    "], [\"id\", \"text\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Make predictions on test documents. cvModel uses the best model found (lrModel).\n",
    "prediction = cvModel.transform(test)\n",
    "selected = prediction.select(\"id\", \"text\", \"probability\", \"prediction\")\n",
    "for row in selected.collect():\n",
    "    print(row)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Apache Toree - PySpark",
   "language": "python",
   "name": "apache_toree_pyspark"
  },
  "language_info": {
   "codemirror_mode": "text/x-ipython",
   "file_extension": ".py",
   "mimetype": "text/x-ipython",
   "name": "python",
   "pygments_lexer": "python",
   "version": "3.6.3\n"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
